<template>
  <div class="container">
    <!-- 检索区域 -->
    <div class="search-area">
      <div class="search-list">
        <div class="search-segment" style="width: 325px">
          <a-input-search
            v-model="query.condition.modelName"
            :max-length="16"
            allow-clear
            placeholder="流程标题"
            search-button
            :button-props="{ type: 'secondary' }"
            long
            @press-enter="onSearch()"
            @search="onSearch()"
          >
            <template #button-icon><icon-search /></template>
          </a-input-search>
        </div>
        <div class="search-segment">
          <a-tooltip content="重置">
            <a-button @click="onSearchReset()"> <icon-refresh /> </a-button>
          </a-tooltip>
        </div>
        <div class="search-segment">
          <a-popover
            position="rt"
            trigger="click"
            :show-arrow="false"
            class="flow-search-more-popover"
            animation-name="riro"
          >
            <a-button> <icon-filter /> </a-button>
            <template #content>
              <!-- 更多检索条件 -->
              <div class="search-more-title">高级筛选</div>
              <div class="search-more-box">
                <a-select
                  v-model:model-value="query.condition.initiatorId"
                  allow-clear
                  allow-search
                  placeholder="发起人"
                >
                  <a-option
                    v-for="user in users"
                    :value="user.id"
                    :key="user.id"
                    :label="user.name"
                  />
                </a-select>
                <a-select
                  class="column"
                  v-model:model-value="query.condition.groupId"
                  allow-clear
                  placeholder="流程分组"
                >
                  <a-option
                    v-for="group in groups"
                    :value="group.id"
                    :key="group.id"
                    :label="group.name"
                  />
                </a-select>
                <a-select
                  class="column"
                  v-model:model-value="query.condition.status"
                  allow-clear
                  placeholder="流程状态"
                  @clear="() => delete query.condition.status"
                >
                  <a-option
                    v-for="(status, idx) in STATUS_LIST"
                    :key="idx"
                    :value="status.value"
                    :label="status.name"
                  />
                </a-select>
                <a-range-picker
                  v-model:model-value="flowBeginTime"
                  :placeholder="['最小提交时间', '最大提交时间']"
                  allow-clear
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  @change="onBeginTimeChanged"
                />
                <a-range-picker
                  v-model:model-value="flowEndTime"
                  :placeholder="['最小完成时间', '最大完成时间']"
                  allow-clear
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  @change="onEndTimeChanged"
                />
              </div>
              <div class="search-more-action">
                <a-button @click="onSearchReset()"> 重置 </a-button>
                <a-button type="primary" @click="onSearch()"> 检索 </a-button>
              </div>
            </template>
          </a-popover>
        </div>
      </div>
      <div class="btns-list">
        <a-tooltip content="导出">
          <a-button :disabled="true"> <icon-export /> </a-button>
        </a-tooltip>
      </div>
    </div>

    <div class="flow-inst-area">
      <div class="flow-table-content">
        <a-alert type="warning" style="margin-bottom: 12px">
          只能是流程发起人本人可处理挂起、作废等操作
        </a-alert>
        <a-table
          :scrollbar="false"
          :bordered="{ cell: true }"
          :data="flowInsts"
          :pagination="false"
          :loading="tableLoading"
          @page-change="onSearch"
          :scroll="{ maxHeight: 'calc(100vh - 227px)', x: 1000 }"
        >
          <template #columns>
            <a-table-column
              title="审批标题"
              data-index="modelName"
            ></a-table-column>
            <a-table-column title="发起人" :width="120" align="center">
              <template #cell="{ record }">
                <flow-node-avatar
                  :size="20"
                  :name="record.creatorName"
                ></flow-node-avatar
              ></template>
            </a-table-column>
            <a-table-column
              title="当前节点"
              :width="100"
              align="center"
              data-index="nodeName"
            >
            </a-table-column>
            <a-table-column title="版本" :width="80" align="center">
              <template #cell="{ record }">
                <a-tag color="arcoblue">{{
                  `v${record.modelVersion || 1}`
                }}</a-tag>
              </template>
            </a-table-column>
            <a-table-column title="状态" :width="100" align="center">
              <template #cell="{ record }">
                <!-- <a-badge
                  :status="INSTANCE_STATUS[record.instanceStatus].status"
                  :text="INSTANCE_STATUS[record.instanceStatus].text"
                /> -->
                <a-tag :color="INSTANCE_STATUS[record.instanceStatus].color">
                  {{ INSTANCE_STATUS[record.instanceStatus].text }}
                </a-tag>
              </template>
            </a-table-column>
            <a-table-column
              title="发起时间"
              data-index="createTime"
              :width="180"
              align="center"
            ></a-table-column>
            <a-table-column
              title="操作"
              :width="210"
              align="center"
              fixed="right"
            >
              <template #cell="{ record }">
                <a-link @click="onDetailOpen(record)"> 详情 </a-link>
                <template v-if="record.instanceStatus == 'SUSPEND'">
                  <a-divider direction="vertical" />
                  <a-popconfirm
                    content="确定要激活该流程么?"
                    @ok="onRestore(record)"
                  >
                    <a-link :disabled="isDisabled(record.creator)">
                      激活
                    </a-link>
                  </a-popconfirm>
                </template>
                <template
                  v-if="
                    record.instanceStatus != 'SUSPEND' &&
                    record.instanceStatus != 'STOP'
                  "
                >
                  <a-divider direction="vertical" />
                  <a-popconfirm
                    content="确定要挂起该流程么?"
                    @ok="onSuspend(record)"
                  >
                    <a-link :disabled="isDisabled(record.creator)">
                      挂起
                    </a-link>
                  </a-popconfirm>
                </template>
                <template v-if="record.instanceStatus != 'STOP'">
                  <a-divider direction="vertical" />
                  <a-popconfirm
                    type="error"
                    content="确定要作废该流程么?"
                    @ok="onStop(record)"
                  >
                    <a-link :disabled="isDisabled(record.creator)">
                      作废
                    </a-link>
                  </a-popconfirm>
                </template>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
      <div class="fenye" v-if="query.total > 0">
        <a-pagination
          size="small"
          show-total
          @change="onSearch"
          :total="query.total"
          :page-size="query.pageSize"
          :current="query.pageIndex"
        />
      </div>
    </div>

    <!-- 流程详情侧边栏 -->
    <a-drawer
      class="flow-card-detail-drawer"
      :width="800"
      :visible="showDetail"
      @ok="onDetailClose()"
      @cancel="onDetailClose()"
      unmountOnClose
      :header="false"
      :footer="false"
    >
      <flow-detail
        v-model:flow-inst="inst"
        :cancelable="false"
        :actionable="false"
        :commentable="false"
      />
    </a-drawer>
  </div>
</template>

<script setup>
import { computed, onBeforeMount, onMounted, ref } from "vue";
import { useOrganStore } from "@/stores";
import { Notification } from "@arco-design/web-vue";
import FlowNodeAvatar from "@/components/common/FlowNodeAvatar.vue";
import FlowDetail from "../../my-flow/flow-detail.vue";
import { INSTANCE_STATUS } from "@/components/flow/common/FlowConstant";
import {
  IconExport,
  IconFilter,
  IconRefresh,
  IconSearch,
  IconClose,
} from "@arco-design/web-vue/es/icon";
import FlowInstApi from "@/api/FlowInstApi";
import OrganApi from "@/api/OrganApi";

let loginUserId = computed(() => {
  return localStorage.getItem("userId");
});
const organStore = useOrganStore();
const users = computed(() => organStore.users);
const flowBeginTime = ref([]);
const flowEndTime = ref([]);
const flowInsts = ref([]);
const tableLoading = ref(false);
const query = ref({
  pageIndex: 1,
  pageSize: 13,
  total: 0,
  condition: { instanceStatus: "PROCESS" },
});

const onBeginTimeChanged = (dateString) => {
  if (dateString && dateString.length == 2) {
    query.value.condition.beginMinTime = dateString[0];
    query.value.condition.beginMaxTime = dateString[1];
  } else {
    delete query.value.condition.beginMinTime;
    delete query.value.condition.beginMaxTime;
  }
};
const onEndTimeChanged = (dateString) => {
  if (dateString && dateString.length == 2) {
    query.value.condition.endMinTime = dateString[0];
    query.value.condition.endMaxTime = dateString[1];
  } else {
    delete query.value.condition.endMinTime;
    delete query.value.condition.endMaxTime;
  }
};

const onSearch = (page) => {
  if (page) query.value.pageIndex = page;
  loadFlowInstance();
};

const onSearchReset = () => {
  console.log("onSearchReset");
  query.value = {
    pageIndex: 1,
    pageSize: 13,
    total: 0,
    condition: { instanceStatus: "PROCESS" },
  };
  onSearch(1);
};

const loadFlowInstance = () => {
  tableLoading.value = true;
  FlowInstApi.pageInsts(query.value)
    .then((resp) => {
      if (resp.code == 0) {
        flowInsts.value = resp.data?.list || [];
        query.value.total = resp.data.total || 0;
      }
      tableLoading.value = false;
    })
    .catch(() => (tableLoading.value = false));
};

// 流程详情
const showDetail = ref(false);
let inst = ref({});
const onDetailOpen = (flowInst) => {
  inst.value = flowInst;
  showDetail.value = true;
};
const onDetailClose = () => {
  showDetail.value = false;
};

const isDisabled = (creator) => {
  return creator && loginUserId.value != creator;
};

// 激活流程
const onRestore = (row) => {
  FlowInstApi.FlowInstRestore({ id: row.id }).then((resp) => {
    if (resp.code == 0) {
      Notification.success(`该流程已恢复`);
      loadFlowInstance();
    }
  });
};
// 暂停
const onSuspend = (row) => {
  FlowInstApi.FlowInstSuspend({ id: row.id }).then((resp) => {
    if (resp.code == 0) {
      Notification.success(`该流程已暂停`);
      loadFlowInstance();
    }
  });
};
// 作废
const onStop = (row) => {
  FlowInstApi.FlowInstStop({ id: row.id }).then((resp) => {
    if (resp.code == 0) {
      Notification.success(`该流程已作废`);
      loadFlowInstance();
    }
  });
};

onBeforeMount(() => {
  OrganApi.loadOrgan();
  loadFlowInstance();
});
</script>
<style lang="less" scoped>
.flow-card-detail-drawer {
}
</style>
